package com.ideaaedi.springcloud.jd.message.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ideaaedi.springcloud.jd.commonds.entity.PageInfo;
import com.ideaaedi.springcloud.jd.commonds.entity.message.po.MsgTemplatePO;
import com.ideaaedi.springcloud.jd.commonds.entity.message.vo.req.MsgTemplateAddReqVO;
import com.ideaaedi.springcloud.jd.commonds.entity.message.vo.req.MsgTemplateBatchAddReqVO;
import com.ideaaedi.springcloud.jd.commonds.entity.message.vo.req.MsgTemplateListReqVO;
import com.ideaaedi.springcloud.jd.commonds.entity.message.vo.req.MsgTemplateUpdateReqVO;
import com.ideaaedi.springcloud.jd.commonds.entity.message.vo.resp.MsgTemplateBatchAddRespVO;
import com.ideaaedi.springcloud.jd.commonds.entity.message.vo.resp.MsgTemplateDetailRespVO;
import com.ideaaedi.springcloud.jd.commonds.entity.message.vo.resp.MsgTemplateListRespVO;
import com.ideaaedi.springcloud.jd.commonspring.mybatisplus.ServiceImplExt;
import com.ideaaedi.springcloud.jd.message.mapper.MsgTemplateMapper;
import com.ideaaedi.springcloud.jd.message.service.MsgTemplateService;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeanUtils;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 消息-模板 服务实现类
 * </p>
 *
 * @author <font size = "20" color = "#3CAA3C"><a href="https://gitee.com/JustryDeng">JustryDeng</a></font> <img src="https://gitee.com/JustryDeng/shared-files/raw/master/JustryDeng/avatar.jpg" />
 * @since 2021.0.5.B
 */
@Service
public class MsgTemplateServiceImpl extends ServiceImplExt<MsgTemplateMapper, MsgTemplatePO> implements MsgTemplateService {

    @Nullable
    @Override
    @Transactional(rollbackFor = Exception.class)
    public MsgTemplateDetailRespVO add(MsgTemplateAddReqVO req, boolean queryDetail) {
        MsgTemplatePO po = new MsgTemplatePO();
        BeanUtils.copyProperties(req, po);
        long id = IdWorker.getId();
        po.setId(id);
        save(po);
        return queryDetail ? detail(id) : null;
    }

    @Override
    public MsgTemplateBatchAddRespVO batchAdd(MsgTemplateBatchAddReqVO req) {
        Boolean ifOneByOne = req.getIfOneByOne();
        Objects.requireNonNull(ifOneByOne, "ifOneByOne cannot be null.");
        List<MsgTemplateBatchAddReqVO.AddItemParamDTO> dataList = req.getDataList();
        MsgTemplateService thisService = (MsgTemplateService) AopContext.currentProxy();
        if (ifOneByOne) {
            for (MsgTemplateBatchAddReqVO.AddItemParamDTO item : dataList) {
                try {
                    thisService.add(item, false);
                    item.setResult(true);
                } catch (Exception e) {
                    item.setResult(false);
                    item.setFailInfo(e.getMessage());
                }
            }
        } else {
            // 出于性能及业务差异考虑, 这里不直接生成. 需要的话，请自己实现
            throw new UnsupportedOperationException("Un-support ifOneByOne is false.");
        }
        MsgTemplateBatchAddRespVO resp = new MsgTemplateBatchAddRespVO();
        resp.setDataList(dataList);
        resp.setIfAllSuccess(dataList.stream().allMatch(x -> x.getResult() != null && x.getResult()));
        return resp;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public MsgTemplateDetailRespVO delete(Long id) {
        Objects.requireNonNull(id, "id cannot be null.");
        MsgTemplateDetailRespVO resp = detail(id);
        removeById(id);
        return resp;
    }

    @Nullable
    @Override
    @Transactional(rollbackFor = Exception.class)
    public MsgTemplateDetailRespVO update(MsgTemplateUpdateReqVO req) {
        Long id = req.getId();
        Objects.requireNonNull(id, "id cannot be null.");
        // mybatis-plus默认的updateById方法，更新策略默认是NOT_NULL（即更新数据时数据为NULL值时将不更新进数据库）
        MsgTemplatePO po = new MsgTemplatePO();
        BeanUtils.copyProperties(req, po);
        updateById(po);
        return detail(id);
    }

    @Nullable
    @Override
    public MsgTemplateDetailRespVO detail(Long id) {
        Objects.requireNonNull(id, "id cannot be null.");
        MsgTemplatePO po = getById(id);
        if (po == null) {
            return null;
        }
        MsgTemplateDetailRespVO resp = new MsgTemplateDetailRespVO();
        BeanUtils.copyProperties(po, resp);
        return resp;
    }
    
    @Override
    public PageInfo<MsgTemplateListRespVO> list(MsgTemplateListReqVO req) {
        int pageNum = req.getPageNum();
        int pageSize = req.getPageSize();
        Long id = req.getId();
        String tenant = req.getTenant();
        String code = req.getCode();
        String name = req.getName();
        String template = req.getTemplate();
        String requiredVarInfo = req.getRequiredVarInfo();
        Integer state = req.getState();
        Integer deleted = req.getDeleted();
        Long createdBy = req.getCreatedBy();
        LocalDateTime createdAt = req.getCreatedAt();
        Long updatedBy = req.getUpdatedBy();
        LocalDateTime updatedAt = req.getUpdatedAt();

        // 分页查
        IPage<MsgTemplatePO> pageInfo = new Page<>(pageNum, pageSize);
        IPage<MsgTemplatePO> page = this.baseMapper.selectPage(pageInfo,
                new LambdaQueryWrapper<MsgTemplatePO>()
            .eq(id != null,  MsgTemplatePO::getId, id)
            .eq(tenant != null && tenant.trim().length() != 0,  MsgTemplatePO::getTenant, tenant)
            .eq(code != null && code.trim().length() != 0,  MsgTemplatePO::getCode, code)
            .eq(name != null && name.trim().length() != 0,  MsgTemplatePO::getName, name)
            .eq(template != null && template.trim().length() != 0,  MsgTemplatePO::getTemplate, template)
            .eq(requiredVarInfo != null && requiredVarInfo.trim().length() != 0,  MsgTemplatePO::getRequiredVarInfo, requiredVarInfo)
            .eq(state != null,  MsgTemplatePO::getState, state)
            .eq(deleted != null,  MsgTemplatePO::getDeleted, deleted)
            .eq(createdBy != null,  MsgTemplatePO::getCreatedBy, createdBy)
            .eq(createdAt != null,  MsgTemplatePO::getCreatedAt, createdAt)
            .eq(updatedBy != null,  MsgTemplatePO::getUpdatedBy, updatedBy)
            .eq(updatedAt != null,  MsgTemplatePO::getUpdatedAt, updatedAt)
            .orderByDesc(MsgTemplatePO::getId)
        );
        // 转换为resp模型
        List<MsgTemplatePO> records = page.getRecords();
        List<MsgTemplateListRespVO> list;
        if (CollectionUtils.isEmpty(records)) {
            list = Collections.emptyList();
        } else {
            list = records.stream().map(po -> {
                MsgTemplateListRespVO resp = new MsgTemplateListRespVO();
                BeanUtils.copyProperties(po, resp);
                return resp;
            }).collect(Collectors.toList());
        }
        return PageInfo.of(page.getTotal(), pageNum, pageSize, list);
    }
}
